package org.foj.model {

import flash.events.EventDispatcher;

import mx.controls.Alert;
import mx.messaging.ChannelSet;
import mx.messaging.Consumer;
import mx.messaging.events.MessageEvent;
import mx.messaging.messages.IMessage;
import mx.rpc.AsyncToken;
import mx.rpc.IResponder;
import mx.rpc.remoting.RemoteObject;

import org.foj.dto.Issue;
import org.foj.event.EventDispatcherFactory;
import org.foj.event.PieChartEvent;
import org.foj.event.UIEvent;

public class IssueModel {

  private var _issueService:RemoteObject;

  public function IssueModel(issueService:RemoteObject = null) {

    if (issueService != null) {
      _issueService = issueService;
    } else {
      var defaultChannelSet:ChannelSet = ChannelSetFactory.getDefaultChannel();

      _issueService = new RemoteObject();
      _issueService.destination = "issueService";
      _issueService.channelSet = defaultChannelSet;
    }

    var messagingChannelSet:ChannelSet = ChannelSetFactory.getMessagingChannel();

    var consumer:Consumer = new Consumer();
    consumer.destination = "flexMessage";
    consumer.channelSet = messagingChannelSet;
    consumer.addEventListener(MessageEvent.MESSAGE, messageHandler);
    consumer.subscribe();

  }

  private function messageHandler(event:MessageEvent):void {
    var eventDispatcher:EventDispatcher = EventDispatcherFactory.getEventDispatcher();

    var refreshEvent:UIEvent = new UIEvent(UIEvent.REFRESH_ISSUES_BUTTON_CLICKED);
    eventDispatcher.dispatchEvent(refreshEvent);

    /*var refreshGraphEvent:UIEvent = new UIEvent(UIEvent.REFRESH_GRAPHS);
    eventDispatcher.dispatchEvent(refreshGraphEvent);*/
  }

  public function getIssues(responder:IResponder):void {
    var asyncToken:AsyncToken = _issueService.getAll();
    asyncToken.addResponder(responder);
  }

  public function getIssue(id:Number, responder:IResponder):void {
    var token:AsyncToken = _issueService.get(id);
    token.addResponder(responder);
  }

  public function saveIssue(issue:Issue, responder:IResponder):void {
    var token:AsyncToken = _issueService.save(issue);
    token.addResponder(responder);
  }

  public function removeIssue(id:Number, responder:IResponder):void {
    var token:AsyncToken = _issueService.remove(id);
    token.addResponder(responder);
  }
}
}
